package com.ljt.business.service.impl;

import com.google.code.kaptcha.Producer;
import com.ljt.response.Result;
import com.ljt.business.entity.Consumer;
import com.ljt.business.mapper.ConsumerMapper;
import com.ljt.business.service.ConsumerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljt.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ljt
 * @since 2021-07-05
 */
@Service
public class ConsumerServiceImpl extends ServiceImpl<ConsumerMapper, Consumer> implements ConsumerService {
    @Autowired
    private Producer producer;

    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/test")
    public Result test(){
        return Result.error();
    }

    @GetMapping("/captcha")
    public Result captcha() throws IOException {
        // hutool工具类生成uuid字符串
        String key = UUID.randomUUID().toString();
        // 生成随机五位验证码
        String code = producer.createText();

        //
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        BASE64Encoder base64Encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";

        String base64Img = str + base64Encoder.encode(outputStream.toByteArray());
        redisUtil.hset("captcha", key, code, 120);

        return Result.ok().data("token", key).data("captchaImg", base64Img.replaceAll("\r|\n", ""));
    }

    @Override
    public List<Consumer> queryConsumerCount() {
        return this.baseMapper.queryConsumerCount();
    }
}
